package tchk.xyz.lingyuntutorminiprogram.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tchk.xyz.lingyuntutorminiprogram.dto.TeacherAuditDTO;
import tchk.xyz.lingyuntutorminiprogram.dto.TeacherCardDTO;
import tchk.xyz.lingyuntutorminiprogram.dto.TeacherDetailDTO;
import tchk.xyz.lingyuntutorminiprogram.dto.TeacherSearchDTO;
import tchk.xyz.lingyuntutorminiprogram.entity.Evaluation;
import tchk.xyz.lingyuntutorminiprogram.entity.SysUser;
import tchk.xyz.lingyuntutorminiprogram.entity.TeacherInfo;
import tchk.xyz.lingyuntutorminiprogram.exception.CustomException;
import tchk.xyz.lingyuntutorminiprogram.mapper.TeacherInfoMapper;
import tchk.xyz.lingyuntutorminiprogram.service.IEvaluationService;
import tchk.xyz.lingyuntutorminiprogram.service.ITeacherInfoService;
import tchk.xyz.lingyuntutorminiprogram.service.IUserService;

import java.util.List;

@Service
public class TeacherInfoServiceImpl extends ServiceImpl<TeacherInfoMapper, TeacherInfo> implements ITeacherInfoService {

    @Autowired
    private IUserService userService;

    @Autowired
    private IEvaluationService evaluationService;

    @Override
    public IPage<TeacherCardDTO> searchTeachers(TeacherSearchDTO searchDTO) {
        IPage<TeacherCardDTO> page = new Page<>(searchDTO.getCurrent(), searchDTO.getSize());
        return this.baseMapper.searchTeachers(page, searchDTO);
    }

    @Override
    public TeacherDetailDTO getTeacherPublicDetailById(Long userId) {
        TeacherInfo teacherInfo = this.getById(userId);
        if (teacherInfo == null || !"approved".equals(teacherInfo.getStatus())) {
            throw new CustomException("教师信息不存在或未通过审核");
        }

        SysUser user = userService.getById(userId);
        if (user == null) {
            throw new CustomException("关联用户信息不存在");
        }

        List<Evaluation> evaluations = evaluationService.list(new LambdaQueryWrapper<Evaluation>()
                .eq(Evaluation::getEvaluateeId, userId)
                .orderByDesc(Evaluation::getCreateTime)
                .last("LIMIT 3"));

        String subjects = "数学,语文"; // 暂时模拟

        TeacherDetailDTO dto = new TeacherDetailDTO();
        dto.setUserId(userId);
        dto.setName(teacherInfo.getRealName());
        dto.setAvatarUrl(user.getAvatarUrl());
        dto.setIsCertified("approved".equals(teacherInfo.getStatus()));
        dto.setIntroduction(teacherInfo.getIntroduction());
        dto.setTeachingExperience(teacherInfo.getTeachingExperience());
        dto.setHourlyRate(teacherInfo.getHourlyRate());
        dto.setOverallScore(teacherInfo.getOverallScore());
        dto.setGrade(teacherInfo.getGrade());
        dto.setTeachingYears(teacherInfo.getTeachingExperienceYear());
        dto.setSubjects(subjects);
        dto.setRecentEvaluations(evaluations);

        return dto;
    }

    @Override
    public IPage<TeacherAuditDTO> getPendingTeachers(IPage<TeacherAuditDTO> page) {
        return this.baseMapper.findPendingTeachers(page);
    }

    @Override
    @Transactional
    public void auditTeacher(Long teacherUserId, Boolean isApproved, String remark) {
        TeacherInfo existingTeacherInfo = this.getById(teacherUserId);
        if (existingTeacherInfo == null || !"pending".equals(existingTeacherInfo.getStatus())) {
            throw new CustomException("教师认证申请不存在或状态不正确");
        }
        LambdaUpdateWrapper<TeacherInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TeacherInfo::getUserId, teacherUserId);
        if (isApproved) {
            updateWrapper.set(TeacherInfo::getStatus, "approved");
            updateWrapper.set(TeacherInfo::getAuditRemark, null);
        } else {
            if (remark == null || remark.isBlank()) {
                throw new CustomException("驳回申请必须填写原因");
            }
            updateWrapper.set(TeacherInfo::getStatus, "rejected");
            updateWrapper.set(TeacherInfo::getAuditRemark, remark);
        }
        this.update(updateWrapper);
    }
}